package LeetCode.exercise;

import java.util.*;

public class LC692 {
    public static void main(String[] args) {
        LC692 main = new LC692();
        String[] words = new String[]{"the","day","is","sunny","the","the","the","sunny","is","is"};
        List<String> list = main.topKFrequent(words, 4);
        System.out.println(list);
    }
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> hashMap = new HashMap<>();
        for(String word: words){
            hashMap.put(word, hashMap.getOrDefault(word, 0) + 1);
        }
        PriorityQueue<Map.Entry<String, Integer>> heap = new PriorityQueue<>((o1, o2) -> {
            if(o1.getValue().equals(o2.getValue())){
                return o2.getKey().compareTo(o1.getKey());
            } else {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()){
            heap.offer(entry);
            if(heap.size() > k){
                heap.poll();
            }
        }
        List<String> list = new ArrayList<>();
        while (!heap.isEmpty()){
            list.add(heap.poll().getKey());
        }
        Collections.reverse(list);
        return list;
    }
}
